package com.huawei.hgip.paintgame.adapter;

import java.util.ArrayList;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.huawei.hgip.paintgame.R;
import com.huawei.hgip.paintgame.m.data.Menu;

/**
 * 主页面菜单适配器
 * @author Administrator
 *
 */
public class MenuListAdapter extends BaseAdapter{
	
	public ArrayList<Menu> menus = new ArrayList<Menu>();
	
	public MenuListAdapter(ArrayList<Menu> menus) {
		this.menus = menus;
	}
	
	public void setMenus(ArrayList<Menu> menus) {
		this.menus = menus;
		notifyDataSetChanged();
	}

	//@Override
	public int getCount() {
		return menus.size();
	}

	//@Override
	public Menu getItem(int position) {
		if (position < menus.size()) {
			return menus.get(position);
		} else {
			return null;
		}
	}

	//@Override
	public long getItemId(int position) {
		Object obj = getItem(position);
		if (position < menus.size()) {
			return ((Menu) obj).getId();
		} else {
			return 0;
		}
	}

	//@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Menu obj = (Menu) getItem(position);
		// 获取界面组件元素
		View rowView = convertView;
		MenuViewCache viewCache;
		if (rowView == null) {
			LayoutInflater inflater = LayoutInflater.from(parent.getContext());
			rowView = inflater.inflate(R.layout.menu_item, null);
			viewCache = new MenuViewCache(rowView);
			rowView.setTag(viewCache);
		} else {
			viewCache = (MenuViewCache) rowView.getTag();
		}
		
		viewCache.getMenuImg().setImageResource(R.drawable.icon);
		viewCache.getMenuName().setText(obj.getName());
		
		return rowView;
	}
	
	
	class MenuViewCache {
		
		private View baseView;
		
		private ImageView menuImg;
		
		private TextView menuName;
		
		public MenuViewCache(View baseView) {
			this.baseView = baseView;
		}

		public ImageView getMenuImg() {
			if (menuImg == null) {
				menuImg = (ImageView) baseView.findViewById(R.id.menu_image);
			}
			return menuImg;
		}

		public TextView getMenuName() {
			if (menuName == null) {
				menuName = (TextView) baseView.findViewById(R.id.menu_name);
			}
			return menuName;
		}
		
		
	}

}
